package com.ahp.user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ahp.constants.ApplicationConstants;
import com.ahp.log.AhpLogFactory;

public class LoginServlet extends HttpServlet {


	//Static Fields
	private static final long serialVersionUID = 6543685378968790138L;
	private static final Logger logger = AhpLogFactory.getLogger(Level.ALL);
	public static final String ADMIN="ADMIN";
	
	
	public void init() throws ServletException {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			logger.log(Level.SEVERE, "JDBC Driver issue", e);
		}
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		if(ApplicationConstants.NONE.equals(login(username, password))){
			resp.sendRedirect("loginError.html");
		} else {
			if (ApplicationConstants.ADMIN.equals(login(username, password))) {
				resp.sendRedirect("scoring.html");
			} else {
				resp.sendRedirect("search.html");
			}
		}
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	private String login(String username, String password) {
		String url ="jdbc:mysql://localhost:3306/mysql";

		try {
			Connection con = DriverManager.getConnection(url,"root", "");
			Statement s = con.createStatement();
			ResultSet resultSet = s.executeQuery("Select * from ahp_v1.ahp_user where ahp_username='"+username+"' and ahp_password='"+password+"'");
			if(resultSet.next()){
				if(resultSet.getBoolean(6)){
					resultSet.close();
					s.close();
					con.close();
					return ApplicationConstants.ADMIN;
				}
				else{
					resultSet.close();
					s.close();
					con.close();
					return ApplicationConstants.USER;
				}
			}
			resultSet.close();
			s.close();
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ApplicationConstants.NONE;
	}

}
